package com.jishe.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.jishe.pojo.Result;
import com.jishe.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求的url
        String url = request.getRequestURL().toString();
        log.info("请求的url是{}", url);
        
        //判断是否包含login
        if (url.contains("login")) {
            log.info("登录操作，放行");
            return true;
        }
        
        //获取请求头中的令牌token
        String jwt = request.getHeader("token");
        if (!StringUtils.hasLength(jwt)) {
            log.info("未登录，返回未登录信息");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        
        //解析token，如果解析失败返回错误结果
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token解析失败，返回未登录信息");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        
        //放行
        log.info("token合法，放行");
        return true;
    }
}
